﻿
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.ComponentModel;
using System.Windows.Media.Imaging;
using System.Windows.Threading;
using OnlineVideos.Data;
using Microsoft.Advertising.Mobile.UI;
using Common.Library;
using OnlineVideos.UI;
using OnlineVideos.Common;
using OnlineVideos.Utilities;
using Common.Utilities;
using Microsoft.Xna.Framework;
using System.IO.IsolatedStorage;
using System.IO;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Phone.Shell;
using Microsoft.Phone.BackgroundAudio;
using System.Xml.Linq;
using Microsoft.Phone.Net.NetworkInformation;
using OnlineVideos.Entities;
using System.Threading.Tasks;


namespace OnlineVideos
{
    public partial class StoryReading : PhoneApplicationPage
    {
        int slidestatus = 0;
        int pagenumber = 1;
        long oldPos1 = 0;
        int previouspage = 0;
        private bool recordclicked = false;
        private bool buttonpressed = false;
        private bool buttontapped = false;
        private bool backpressed = false;
        private bool stopclicked = false;
        private bool recordstopped = false;
        IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication();
        private Microphone mic = Microphone.Default;
        bool CancelEvents = false;
        static bool pagenavigatedback = false;
        private MemoryStream memstream = null;
        private byte[] buffer = null;

        public StoryReading()
        {
            InitializeComponent();
            DispatcherTimer dt = new DispatcherTimer();
            dt.Tick += new EventHandler(dt_Tick);
            dt.Interval = TimeSpan.FromMilliseconds(33);
            dt.Start();
            
        }


        void mic_BufferReady(object sender, EventArgs e)
        {
            mic.GetData(buffer);
            memstream.Write(buffer, 0, buffer.Length);

        }

        void dt_Tick(object sender, EventArgs e)
        {
            try
            {
                FrameworkDispatcher.Update();
            }
            catch
            {
            }
        }
        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            ShowList objlist = OnlineShow.GetShowDetail(AppSettings.ShowUniqueID);
            txttitle.Text = objlist.Title;
            if (ResourceHelper.AppName == Apps.Vedic_Library.ToString() && objlist.SubTitle == Constants.MovieCategoryTelugu)
            {
                txtDescription.FontFamily = new FontFamily("/Pothana2000.ttf#Pothana2000");
                txtDescription.FontSize = 31;
            }
            if (objlist.SubTitle == Constants.MovieCategoryEnglish)
            {
                if (ResourceHelper.AppName == Apps.Story_Time.ToString())
                {
                    txtDescription.FontFamily = new FontFamily("/COM4NRG_.TTF#COM4t Nuvu Regular");
                    txtDescription.FontSize = 34;
                }
                else
                {
                    txtDescription.FontSize = 24;
                }
            }
            if (ResourceHelper.AppName == Apps.Vedic_Library.ToString() && objlist.SubTitle == Constants.MovieCategoryHindi)
            {
                txtDescription.FontFamily = new FontFamily("/CDACOTYGB.TTF#CDAC-GISTYogesh");
                txtDescription.FontSize = 26;
            }

            try
            {
                loadingblock.Visibility = Visibility.Visible;
                //_performanceProgressBar.Visibility = Visibility.Visible;
                //_performanceProgressBar.IsIndeterminate = true;
             
                if (ResourceHelper.AppName == Apps.Vedic_Library.ToString() && Constants.mode == "Listenmp3")
                {
                    string title = StoryManager.GetTitle(AppSettings.ShowUniqueID);
                    if (!Task.Run(async()=>await Storage.FileExists(title + ".mp3")).Result)
                    {
                        
                        if (NetworkInterface.GetIsNetworkAvailable() && NetworkInterface.NetworkInterfaceType != NetworkInterfaceType.None)
                        {
                            ShowLinks objlinks = new ShowLinks();
                            Constants.Downloadedstream = default(Stream);
                            WebClient web = new WebClient();
                            objlinks = (OnlineShow.GetAudioLinks(AppSettings.ShowID, LinkType.Audio));
                            web.OpenReadAsync(new Uri(objlinks.LinkUrl, UriKind.Absolute));
                            web.OpenReadCompleted += new OpenReadCompletedEventHandler(web_OpenReadCompleted);
                        }


                        else
                        {
                            Constants.mode = "Read";
                            Loaded += new RoutedEventHandler(StoryReading_Loaded);
                        }
                    }


                    else
                    {
                        Loaded += new RoutedEventHandler(StoryReading_Loaded);
                    }
                }
                else
                {

                    Loaded += new RoutedEventHandler(StoryReading_Loaded);
                }
            }
            catch (Exception ex)
            {
                Exceptions.SaveOrSendExceptions("Exception in OnNavigatedTo Method In StoryReading file", ex);
                string excepmess = "Exception in OnNavigatedTo Method In StoryReading file.\n\n" + ex.Message + "\n\n StackTrace :- \n" + ex.StackTrace;
            }
        }

        private void web_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
        {
            try
            {
                if (e.Error == null)
                {
                    Constants.Downloadedstream = e.Result;

                    StoryReadingExperience.StartRetriving(this.ContentPanel);
                    StoryReadingExperience.RetriveFromStorage(this.imgstory, txtDescription, txtpage, pagenumber, this.ContentPanel, Constants.mode == "Listenmp3" ? this.me : null, buttontapped);
                 
                    if (ResourceHelper.AppName == Apps.Vedic_Library.ToString())
                        this.me.MediaEnded -= me_MediaEnded;

                }
                else
                {
                    Constants.mode = "Read";
                    Loaded += new RoutedEventHandler(StoryReading_Loaded);
                }
                loadingblock.Visibility = Visibility.Collapsed;
                //_performanceProgressBar.IsIndeterminate = false;
                //_performanceProgressBar.Visibility = Visibility.Collapsed;
            }
            catch (Exception ex)
            {
                Exceptions.SaveOrSendExceptions("Exception in web_OpenReadCompleted Method In StoryReading file", ex);
                string excepmess = "Exception in web_OpenReadCompleted Method In StoryReading file.\n\n" + ex.Message + "\n\n StackTrace :- \n" + ex.StackTrace;
            }
        }               
        private void StoryReading_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
               // txttitle.Text = StoryManager.GetTitle(AppSettings.ShowUniqueID);
                StoryReadingExperience.StartRetriving(this.ContentPanel);
                if (ResourceHelper.AppName == Apps.Vedic_Library.ToString() && Constants.mode == "Listenmp3")
                    StoryReadingExperience.RetriveFromStorage(this.imgstory, txtDescription, txtpage, pagenumber, this.ContentPanel, Constants.mode == "Listenmp3" ? this.me : null, buttontapped);
                else
                    StoryReadingExperience.RetriveFromStorage(this.imgstory, txtDescription, txtpage, pagenumber, this.ContentPanel, Constants.mode == "Listen" ? this.me : null, buttontapped);
                if (ResourceHelper.AppName == Apps.Vedic_Library.ToString() && Constants.mode == "Listenmp3")
                    this.me.MediaEnded -= me_MediaEnded;
                else
                {
                    this.me.MarkerReached -= me_MarkerReached;
                    this.me.MediaOpened -= me_MediaOpened;
                }
                loadingblock.Visibility = Visibility.Collapsed;
                //_performanceProgressBar.IsIndeterminate = false;
                //_performanceProgressBar.Visibility = Visibility.Collapsed;
                if (Constants.mode == "Rec")
                    showstack();

                if (Constants.mode == "Rec" && StoryReadingExperience.storyDictionary.Count == getcount())
                {
                    List<Stories> stories = Constants.connection.Table<Stories>().OrderByDescending(k => k.ID).ToListAsync().Result.Take(1).ToList();
                    //IQueryable<Stories> stories = (from k in context.storyTable
                    //                               orderby k.ID descending

                    //                               select k).Take(1);

                    foreach (Stories s in stories)
                    {
                        s.RecordCompleted = false;
                        Constants.connection.UpdateAsync(s);
                    }
                   

                }
            }
            catch (Exception ex)
            {
                Exceptions.SaveOrSendExceptions("Exception in StoryReading_Loaded In StoryReading file", ex);
                string excepmess = "Exception in StoryReading_Loaded In StoryReading file.\n\n" + ex.Message + "\n\n StackTrace :- \n" + ex.StackTrace;
            }
          

        }
        private void StackPanel_ManipulationDelta(object sender, ManipulationDeltaEventArgs e)
        {
            try
            {
                slidestatus++;
                if (slidestatus == 1)
                {
                    if (Constants.mode == "Rec")
                    {
                        if (recordclicked == true)
                        {
                            stop_Click_1();

                        }
                    }
                    pagenumber = StoryReadingExperience.storystackmanipulationdelta(e, pagenumber, slidestatus, this.mainstk);
                    if (Constants.mode == "Rec" && previouspage > pagenumber && recordclicked == true)
                    {
                        pagenavigatedback = true;
                    }

                    previouspage = pagenumber;
                    return;
                }
            }
            catch (Exception ex)
            {
                Exceptions.SaveOrSendExceptions("Exception in StackPanel_ManipulationDelta method In StoryReading file", ex);
                string excepmess = "Exception in StackPanel_ManipulationDelta method In StoryReading file.\n\n" + ex.Message + "\n\n StackTrace :- \n" + ex.StackTrace;
            }
        }
        private void StackPanel_ManipulationCompleted(object sender, ManipulationCompletedEventArgs e)
        {
            try
            {
                if (slidestatus > 0)
                {
                    if (Constants.mode == "Listen")
                    {

                        me.Stop();
                        me.Source = null;

                    }
                    if (Constants.mode != "Listenmp3")
                    {
                        slidestatus = StoryReadingExperience.storystackmanipulationCompleted(this.imgstory, this.txtDescription, this.txtpage, pagenumber, this.ContentPanel, Constants.mode == "Listen" ? this.me : null, buttontapped);
                        this.messagestk.Visibility = Visibility.Collapsed;
                    }

                    if (Constants.mode == "Listenmp3")
                    {

                        me.Stop();
                        me.Source = null;
                        slidestatus = StoryReadingExperience.storystackmanipulationCompleted(this.imgstory, this.txtDescription, this.txtpage, pagenumber, this.ContentPanel, Constants.mode == "Listenmp3" ? this.me : null, buttontapped);
                        this.messagestk.Visibility = Visibility.Collapsed;
                    }
                    if (Constants.mode == "Rec")
                    {
                        showstack();

                    }

                }
                else
                {
                    if (Constants.mode != "Read")
                    {
                        showstack();
                        if (Constants.mode == "Listen")
                        {
                            DispatcherTimer buttonTimer = new DispatcherTimer();
                            buttonTimer.Interval = TimeSpan.FromSeconds(10);
                            buttonTimer.Tick += new EventHandler(buttonTimer_Tick);
                            buttonTimer.Start();
                        }
                    }

                }

            }

            catch (Exception ex)
            {
                Exceptions.SaveOrSendExceptions("Exception in StackPanel_ManipulationCompleted method In StoryReading file", ex);
                string excepmess = "Exception in StackPanel_ManipulationCompleted method In StoryReading file.\n\n" + ex.Message + "\n\n StackTrace :- \n" + ex.StackTrace;
            }

        }

        void buttonTimer_Tick(object sender, EventArgs e)
        {
            messagestk.Visibility = Visibility.Collapsed;
            (sender as DispatcherTimer).Stop();
        }
        public int getcount()
        {
            int count = 0;
            if (Task.Run(async()=>await Storage.FileExists("/StoryRecordings/" + AppSettings.ShowID + "/StoryRecordings.xml")).Result)
            {
                XDocument xdoc = Storage.ReadFileAsDocument("/StoryRecordings/" + AppSettings.ShowID + "/StoryRecordings.xml");
                var data = xdoc.Descendants("Stories").Elements("Story").Elements("End").Select(i => i.Value).ToList();

                count = data.Count();
            }
            return count;
        }
        private void record_Click()
        {
            try
            {

                IsolatedStorageFile isoStore2 = IsolatedStorageFile.GetUserStoreForApplication();
                recordclicked = true;
                stopclicked = false;
                mic.BufferDuration = TimeSpan.FromMilliseconds(500);
                buffer = new byte[mic.GetSampleSizeInBytes(mic.BufferDuration)];
                mic.BufferReady += new EventHandler<EventArgs>(mic_BufferReady);
                if (isoStore2.FileExists("/StoryRecordings/" + AppSettings.ShowID + "/" + AppSettings.Title + ".wav"))
                {

                    if (!checkxml(pagenumber))
                    {
                        memstream = new MemoryStream();
                        WriteWavHeader(memstream, mic.SampleRate);
                        IsolatedStorageFileStream fs = isoStore2.OpenFile(@"/StoryRecordings/" + AppSettings.ShowID + "/" + AppSettings.Title + ".wav", FileMode.Open, FileAccess.Read);
                        byte[] arrfile = new byte[fs.Length - 44];
                        fs.Position = 44;
                        fs.Read(arrfile, 0, arrfile.Length);
                        memstream.Write(arrfile, 0, arrfile.Length);
                        fs.Close();
                        oldPos1 = memstream.Position;
                    }
                    else
                    {
                        deleteaudio(pagenumber - 1);
                    }

                }
                if (getcount() == 0)
                {
                    memstream = new MemoryStream();
                    WriteWavHeader(memstream, mic.SampleRate);
                }
                mic.Start();
            }
            catch (Exception ex)
            {
                Exceptions.SaveOrSendExceptions("Exception in record_Click() method In StoryReading file", ex);
                string excepmess = "Exception in record_Click() method In StoryReading file.\n\n" + ex.Message + "\n\n StackTrace :- \n" + ex.StackTrace;
            }

        }
        private void stop_Click_1()
        {
            try
            {
                long beginp = oldPos1;
                long endp = memstream.Position;

                mic.Stop();
                stopclicked = true;
                mic.BufferReady -= new EventHandler<EventArgs>(mic_BufferReady);
                if (memstream != default(MemoryStream))
                {

                    writeFile(memstream);

                }
                if (Constants.mode == "Rec" && recordclicked == true)
                {
                    savexml(pagenumber, beginp, endp);
                    memstream = default(MemoryStream);
                    recordclicked = false;
                }

                if (Constants.mode == "Rec" && StoryReadingExperience.storyDictionary.Count == getcount())
                {
                    int showid=Convert.ToInt32(AppSettings.ShowID);
                    List<Stories> stories = Task.Run(async () => await Constants.connection.Table<Stories>().Where(i => i.ShowID == showid).OrderByDescending(k => k.ID).ToListAsync()).Result.Take(1).ToList();
                    //IQueryable<Stories> stories = (from k in context.storyTable
                    //                               where k.ShowID == Convert.ToInt32(AppSettings.ShowID)
                    //                               orderby k.ID descending

                    //                               select k).Take(1);

                    foreach (Stories s in stories)
                    {
                        s.RecordCompleted = true;
                        Constants.connection.UpdateAsync(s);
                    }
                  
                }
            }
            catch (Exception ex)
            {
                Exceptions.SaveOrSendExceptions("Exception in stop_Click_1 method In StoryReading file", ex);
                string excepmess = "Exception in stop_Click_1 method In StoryReading file.\n\n" + ex.Message + "\n\n StackTrace :- \n" + ex.StackTrace;
            }

        }
        public void addaudio()
        {

            try
            {
                if (Task.Run(async()=>await Storage.FileExists("/StoryRecordings/" + AppSettings.ShowID + "/StoryRecordings.xml")).Result)
                {
                    IsolatedStorageFile isoStore1 = IsolatedStorageFile.GetUserStoreForApplication();
                    IsolatedStorageFileStream isostream = default(IsolatedStorageFileStream);
                    XDocument xdoc = default(XDocument);
                    isostream = new IsolatedStorageFileStream("/StoryRecordings/" + AppSettings.ShowID + "/StoryRecordings.xml", FileMode.Open, isoStore1);
                    xdoc = XDocument.Load(isostream);
                    isostream.Close();

                    var data = xdoc.Descendants("Stories").Elements("Story").SingleOrDefault(i => (int)i.Attribute("Id") == pagenumber).Elements().Where(i => i.Name == "End").Select(i => i.Value);
                    if (data != null)
                    {
                        if (isoStore.FileExists("/StoryRecordings/" + AppSettings.ShowID + "/" + AppSettings.Title + ".wav"))
                        {

                            IsolatedStorageFileStream fs = isoStore.OpenFile(@"/StoryRecordings/" + AppSettings.ShowID + "/" + AppSettings.Title + ".wav", FileMode.Open, FileAccess.Read);
                            byte[] arrfile = new byte[fs.Length - Convert.ToInt32(data.First().ToString())];
                            fs.Position = Convert.ToInt32(data.First().ToString());
                            fs.Read(arrfile, 0, arrfile.Length);
                            memstream.Write(arrfile, 0, arrfile.Length);
                            fs.Close();

                        }
                    }

                }


            }
            catch (NullReferenceException ex)
            {

            }
        }
        public void deleteaudio(int pagenum)
        {
            try
            {
                if (pagenum == 0)
                {
                    if (isoStore.FileExists("/StoryRecordings/" + AppSettings.ShowID + "/" + AppSettings.Title + ".wav"))
                    {
                        memstream = new MemoryStream();
                        WriteWavHeader(memstream, mic.SampleRate);
                        oldPos1 = 0;

                    }
                }
                else
                {

                    if (Task.Run(async()=>await Storage.FileExists("/StoryRecordings/" + AppSettings.ShowID + "/StoryRecordings.xml")).Result)
                    {
                        IsolatedStorageFile isoStore1 = IsolatedStorageFile.GetUserStoreForApplication();
                        IsolatedStorageFileStream isostream = default(IsolatedStorageFileStream);
                        XDocument xdoc = default(XDocument);
                        isostream = new IsolatedStorageFileStream("/StoryRecordings/" + AppSettings.ShowID + "/StoryRecordings.xml", FileMode.Open, isoStore1);
                        xdoc = XDocument.Load(isostream);
                        isostream.Close();

                        var data = xdoc.Descendants("Stories").Elements("Story").SingleOrDefault(i => (int)i.Attribute("Id") == pagenum).Elements().Where(i => i.Name == "End").Select(i => i.Value);
                        if (data != null)
                        {
                            if (isoStore.FileExists("/StoryRecordings/" + AppSettings.ShowID + "/" + AppSettings.Title + ".wav"))
                            {
                                memstream = new MemoryStream();
                                WriteWavHeader(memstream, mic.SampleRate);
                                IsolatedStorageFileStream fs = isoStore.OpenFile(@"/StoryRecordings/" + AppSettings.ShowID + "/" + AppSettings.Title + ".wav", FileMode.Open, FileAccess.Read);
                                byte[] arrfile = new byte[fs.Length - 44];
                                fs.Position = 44;

                                fs.Read(arrfile, 0, arrfile.Length);
                                memstream.Write(arrfile, 0, arrfile.Length);
                                memstream.SetLength(Convert.ToInt32(data.First().ToString()));
                                oldPos1 = memstream.Position;
                                fs.Close();

                            }
                        }

                    }
                }
            }
            catch (Exception ex)
            {
                Exceptions.SaveOrSendExceptions("Exception in deleteaudio method In StoryReading file", ex);
                string excepmess = "Exception in deleteaudio method In StoryReading file.\n\n" + ex.Message + "\n\n StackTrace :- \n" + ex.StackTrace;
            }
        }
        public void updatexml(int pagenum, long BeginTime, long EndTime)
        {
            try
            {
                if (Task.Run(async()=>await Storage.FileExists("/StoryRecordings/" + AppSettings.ShowID + "/StoryRecordings.xml")).Result)
                {
                    int count = 0;
                    long replaceendtime = 0;
                    int difference = 0;
                    IsolatedStorageFile isoStore1 = IsolatedStorageFile.GetUserStoreForApplication();
                    IsolatedStorageFileStream isostream = default(IsolatedStorageFileStream);
                    XDocument xdoc = default(XDocument);
                    isostream = new IsolatedStorageFileStream("/StoryRecordings/" + AppSettings.ShowID + "/StoryRecordings.xml", FileMode.Open, isoStore1);
                    xdoc = XDocument.Load(isostream);
                    isostream.Close();
                    var data = xdoc.Descendants("Stories").Elements("Story").Where(i => Convert.ToInt32(i.Attribute("Id").Value) >= pagenum).OrderBy(i => Convert.ToInt32(i.Attribute("Id").Value));
                    if (data != null)
                    {
                        foreach (XElement itemElement in data)
                        {
                            if (count == 0)
                            {
                                itemElement.SetElementValue("Begin", BeginTime);
                                itemElement.SetElementValue("End", EndTime);
                                replaceendtime = EndTime;
                                count++;

                            }
                            else
                            {
                                difference = Convert.ToInt32(itemElement.Element("End").Value) - Convert.ToInt32(itemElement.Element("Begin").Value);
                                itemElement.SetElementValue("Begin", replaceendtime);
                                itemElement.SetElementValue("End", replaceendtime + difference);
                                replaceendtime = replaceendtime + difference;
                            }
                        }
                    }
                    isostream = new IsolatedStorageFileStream("/StoryRecordings/" + AppSettings.ShowID + "/StoryRecordings.xml", FileMode.Create, isoStore);
                    xdoc.Save(isostream);
                    isostream.Close();
                    isoStore1.Dispose();
                }
            }
            catch (Exception ex)
            {
                Exceptions.SaveOrSendExceptions("Exception in updatexml method In StoryReading file", ex);
                string excepmess = "Exception in updatexml method In StoryReading file.\n\n" + ex.Message + "\n\n StackTrace :- \n" + ex.StackTrace;
            }
        }
        public bool checkxml(int pagenum)
        {

            bool exists = false;
            try
            {
                if (Task.Run(async()=>await Storage.FileExists("/StoryRecordings/" + AppSettings.ShowID + "/StoryRecordings.xml")).Result)
                {
                    IsolatedStorageFile isoStore1 = IsolatedStorageFile.GetUserStoreForApplication();
                    IsolatedStorageFileStream isostream = default(IsolatedStorageFileStream);
                    XDocument xdoc = default(XDocument);
                    isostream = new IsolatedStorageFileStream("/StoryRecordings/" + AppSettings.ShowID + "/StoryRecordings.xml", FileMode.Open, isoStore1);
                    xdoc = XDocument.Load(isostream);
                    isostream.Close();
                    var data = (from p in xdoc.Descendants("Stories").Elements() where p.Attribute("Id").Value == pagenum.ToString() select p).ToList();
                    if (data.Count() > 0)
                        exists = true;

                    isoStore1.Dispose();
                }

            }
            catch (Exception ex)
            {
                Exceptions.SaveOrSendExceptions("Exception in checkxml method In StoryReading file", ex);
                string excepmess = "Exception in checkxml method In StoryReading file.\n\n" + ex.Message + "\n\n StackTrace :- \n" + ex.StackTrace;
            }
            return exists;
        }
        private void savexml(int pagenum, long BeginTime, long EndTime)
        {
            try
            {
                int pageno = 0;

                if (recordstopped == true)
                {

                    recordstopped = false;
                }


                pageno = pagenum;

                if (!Storage.DirectoryExists("/StoryRecordings/" + AppSettings.ShowID))
                    Storage.CreateDirectory("/StoryRecordings/" + AppSettings.ShowID);

                if (Task.Run(async()=>await Storage.FileExists("/StoryRecordings/" + AppSettings.ShowID + "/StoryRecordings.xml")).Result)
                {
                    if (checkxml(pageno))
                    {
                        updatexml(pageno, BeginTime, EndTime);

                    }


                    else
                    {
                        IsolatedStorageFile isoStore1 = IsolatedStorageFile.GetUserStoreForApplication();
                        IsolatedStorageFileStream isostream = default(IsolatedStorageFileStream);
                        XDocument xdoc = default(XDocument);
                        isostream = new IsolatedStorageFileStream("/StoryRecordings/" + AppSettings.ShowID + "/StoryRecordings.xml", FileMode.Open, isoStore1);
                        xdoc = XDocument.Load(isostream);
                        isostream.Close();
                        xdoc.Root.Add(new XElement("Story",
                                new XAttribute("Id", pageno),
                                new XElement("Begin", BeginTime),
                                new XElement("End", EndTime)));
                        isostream = new IsolatedStorageFileStream("/StoryRecordings/" + AppSettings.ShowID + "/StoryRecordings.xml", FileMode.Create, isoStore);
                        xdoc.Save(isostream);
                        isostream.Close();
                        isoStore1.Dispose();
                    }
                }
                else
                {
                    IsolatedStorageFile isoStore1 = IsolatedStorageFile.GetUserStoreForApplication();
                    IsolatedStorageFileStream isostream = default(IsolatedStorageFileStream);
                    XDocument xdoc = default(XDocument);
                    isostream = new IsolatedStorageFileStream("/StoryRecordings/" + AppSettings.ShowID + "/StoryRecordings.xml", FileMode.Create, isoStore1);
                    xdoc = new XDocument(new XDeclaration("1.0", "utf-8", "yes"),
                        new XElement("Stories",
                        new XElement("Story",
                        new XAttribute("Id", pageno),
                        new XElement("Begin", BeginTime),
                         new XElement("End", EndTime))));
                    xdoc.Save(isostream);
                    isostream.Close();
                    isoStore1.Dispose();
                }
            }
            catch (Exception ex)
            {
                Exceptions.SaveOrSendExceptions("Exception in savexml method In StoryReading file", ex);
                string excepmess = "Exception in savexml method In StoryReading file.\n\n" + ex.Message + "\n\n StackTrace :- \n" + ex.StackTrace;
            }
        }
        private void writeFile(MemoryStream s)
        {
            try
            {
                if (!Storage.DirectoryExists("/StoryRecordings/" + AppSettings.ShowID))
                    Storage.CreateDirectory("/StoryRecordings/" + AppSettings.ShowID);
                using (var userStore = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    if (isoStore.FileExists("/StoryRecordings/" + AppSettings.ShowID + "/" + AppSettings.Title + ".wav"))
                    {
                        int pageno = 0;

                        if (pagenavigatedback == true)
                        {
                            pageno = pagenumber;
                        }
                        else
                        {
                            pageno = pagenumber;
                        }

                        if (checkxml(pageno))
                        {
                            addaudio();

                        }
                        using (var file = userStore.OpenFile("/StoryRecordings/" + AppSettings.ShowID + "/" + AppSettings.Title + ".wav", FileMode.Create))
                        {

                            UpdateWavHeader(memstream);
                            s.WriteTo(file);
                        }

                    }
                    else
                    {
                        using (var file = userStore.OpenFile("/StoryRecordings/" + AppSettings.ShowID + "/" + AppSettings.Title + ".wav", FileMode.Create))
                        {

                            UpdateWavHeader(memstream);
                            s.WriteTo(file);
                        }
                    }

                }
            }
            catch (Exception ex)
            {
                Exceptions.SaveOrSendExceptions("Exception in writeFile method In StoryReading file", ex);
                string excepmess = "Exception in writeFile method In StoryReading file.\n\n" + ex.Message + "\n\n StackTrace :- \n" + ex.StackTrace;
            }

        }
        public void WriteWavHeader(Stream stream, int sampleRate)
        {
            const int bitsPerSample = 16;
            const int bytesPerSample = bitsPerSample / 8;
            var encoding = System.Text.Encoding.UTF8;
            stream.Write(encoding.GetBytes("RIFF"), 0, 4);
            stream.Write(BitConverter.GetBytes(0), 0, 4);
            stream.Write(encoding.GetBytes("WAVE"), 0, 4);
            stream.Write(encoding.GetBytes("fmt "), 0, 4);
            stream.Write(BitConverter.GetBytes(16), 0, 4);
            stream.Write(BitConverter.GetBytes((short)1), 0, 2);
            stream.Write(BitConverter.GetBytes((short)1), 0, 2);
            stream.Write(BitConverter.GetBytes(sampleRate), 0, 4);
            stream.Write(BitConverter.GetBytes(sampleRate * bytesPerSample), 0, 4);
            stream.Write(BitConverter.GetBytes((short)(bytesPerSample)), 0, 2);
            stream.Write(BitConverter.GetBytes((short)(bitsPerSample)), 0, 2);
            stream.Write(encoding.GetBytes("data"), 0, 4);
            stream.Write(BitConverter.GetBytes(0), 0, 4);
        }
        private void me_MediaEnded(object sender, RoutedEventArgs e)
        {
            try
            {
                if (Task.Run(async()=>await Storage.FileExists("/StoryRecordings/" + AppSettings.ShowID + "/StoryRecordings.xml")).Result)
                {
                    XDocument xdoc = Storage.ReadFileAsDocument("/StoryRecordings/" + AppSettings.ShowID + "/StoryRecordings.xml");

                    var data = from f in xdoc.Descendants("Stories").Elements("Story")
                               where (Convert.ToInt32(f.Attribute("Id").Value)) == pagenumber + 1
                               select f;

                    if (Task.Run(async()=>await Storage.FileExists("/StoryRecordings/" + AppSettings.ShowID + "/" + AppSettings.Title + ".wav")).Result && data.Count() > 0)
                    {
                        StackPanel_ManipulationDelta(null, null);
                        StackPanel_ManipulationCompleted(null, null);
                    }

                }
            }
            catch (Exception ex)
            {
                Exceptions.SaveOrSendExceptions("Exception in me_MediaEnded In StoryReading file", ex);
                string excepmess = "Exception in me_MediaEnded In StoryReading file.\n\n" + ex.Message + "\n\n StackTrace :- \n" + ex.StackTrace;
            }
        }
        public void UpdateWavHeader(Stream stream)
        {
            var oldPos = stream.Position;
            stream.Seek(4, SeekOrigin.Begin);
            stream.Write(BitConverter.GetBytes((int)stream.Length - 8), 0, 4);
            stream.Seek(40, SeekOrigin.Begin);
            stream.Write(BitConverter.GetBytes((int)stream.Length - 44), 0, 4);
            stream.Seek(oldPos, SeekOrigin.Begin);
        }
        protected override void OnBackKeyPress(CancelEventArgs e)
        {
            try
            {
                Constants.Downloadedstream = default(Stream);
                string title = StoryManager.GetTitle(AppSettings.ShowUniqueID);
                IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication();
                if (Constants.mode == "Listenmp3")
                {
                    if (me.CurrentState == MediaElementState.Playing || me.CurrentState == MediaElementState.Paused)
                        me.Stop();
                    me.Source = null;
                    if (isoStore.FileExists(title + ".mp3") && ResourceHelper.ProjectName == "Vedic Library")
                    {
                        //isoStore.DeleteFile(title + ".mp3");

                    }
                }
                backpressed = true;
                if (recordclicked == true && Constants.mode == "Rec")
                {
                    stop_Click_1();
                }
            }
            catch (Exception ex)
            {
                Exceptions.SaveOrSendExceptions("Exception in OnBackKeyPress In StoryReading file", ex);
                string excepmess = "Exception in OnBackKeyPress In StoryReading file.\n\n" + ex.Message + "\n\n StackTrace :- \n" + ex.StackTrace;
            }

        }
        private void resume_Click(object sender, MouseButtonEventArgs e)
        {
            try
            {
                buttonpressed = true;

                if (Constants.mode == "Listen" || Constants.mode == "Listenmp3")
                {
                    if (me.CurrentState == MediaElementState.Playing)
                    {
                        me.Pause();
                        buttontapped = true;
                        this.messagestk.Visibility = Visibility.Collapsed;
                        return;

                    }

                    else
                    {
                        me.Play();
                        buttontapped = false;
                        this.messagestk.Visibility = Visibility.Collapsed;
                        return;
                    }

                }

                if (Constants.mode == "Rec")
                {
                    if (((BitmapImage)this.Resume.Source).UriSource.ToString().Contains("record.png"))
                    {
                        record_Click();
                        this.Resume.Source = new BitmapImage(new Uri("/Images/Record Icons/stop.png", UriKind.RelativeOrAbsolute));
                        this.messagestk.Visibility = Visibility.Collapsed;
                        return;
                    }
                    else
                    {
                        recordstopped = true;
                        stop_Click_1();
                        this.Resume.Source = new BitmapImage(new Uri("/Images/Record Icons/record.png", UriKind.RelativeOrAbsolute));
                        this.messagestk.Visibility = Visibility.Collapsed;
                        return;
                    }
                }
            }
            catch (Exception ex)
            {
                Exceptions.SaveOrSendExceptions("Exception in resume_Click In StoryReading file", ex);
                string excepmess = "Exception in resume_Click In StoryReading file.\n\n" + ex.Message + "\n\n StackTrace :- \n" + ex.StackTrace;
            }

        }
        private void Resume_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                if (Constants.mode == "Rec" && recordclicked == true)
                {
                    this.Resume.Source = new BitmapImage(new Uri("/Images/Record Icons/stop.png", UriKind.RelativeOrAbsolute));

                }
                else if (Constants.mode == "Rec" && recordclicked == false)
                {
                    this.Resume.Source = new BitmapImage(new Uri("/Images/Record Icons/record.png", UriKind.RelativeOrAbsolute));
                }
                else if (Constants.mode == "Listen" && me.CurrentState != MediaElementState.Playing)
                {
                    this.Resume.Margin = new Thickness(0, 50, 0, 10);
                    this.message.Margin = new Thickness(35, 0, 10, 0);
                    this.Resume.Source = new BitmapImage(new Uri("/Images/Record Icons/play.png", UriKind.RelativeOrAbsolute));
                }
                else if (Constants.mode == "Listen")
                {
                    this.Resume.Margin = new Thickness(0, 50, 0, 10);
                    this.message.Margin = new Thickness(30, 0, 10, 0);
                    this.Resume.Source = new BitmapImage(new Uri("/Images/Record Icons/pause.png", UriKind.RelativeOrAbsolute));
                }
                else if (Constants.mode == "Listenmp3" && me.CurrentState != MediaElementState.Playing)
                {
                    this.Resume.Margin = new Thickness(0, 50, 0, 10);
                    this.message.Margin = new Thickness(35, 0, 10, 0);
                    this.Resume.Source = new BitmapImage(new Uri("/Images/Record Icons/play.png", UriKind.RelativeOrAbsolute));
                }
                else if (Constants.mode == "Listenmp3")
                {
                    this.Resume.Margin = new Thickness(0, 50, 0, 10);
                    this.message.Margin = new Thickness(30, 0, 10, 0);
                    this.Resume.Source = new BitmapImage(new Uri("/Images/Record Icons/pause.png", UriKind.RelativeOrAbsolute));
                }
            }
            catch (Exception ex)
            {
                Exceptions.SaveOrSendExceptions("Exception in Resume_Loaded In StoryReading file", ex);
                string excepmess = "Exception in Resume_Loaded In StoryReading file.\n\n" + ex.Message + "\n\n StackTrace :- \n" + ex.StackTrace;
            }
        }
        private void showstack()
        {
            try
            {
                if (buttonpressed == false)
                {
                    if (Constants.mode == "Rec" && Convert.ToInt32(txtpage.Text.Substring(0, txtpage.Text.IndexOf('/'))) <= getcount() && recordclicked == false)
                    {
                        this.Resume.Source = new BitmapImage(new Uri("/Images/Record Icons/record.png", UriKind.RelativeOrAbsolute));
                        message.Text = "Tap to re-record voice for page " + txtpage.Text.Substring(0, txtpage.Text.IndexOf('/'));
                        StoryReadingExperience.storystackmouseenter(this.messagestk);
                    }
                    else if (Constants.mode == "Rec" && Convert.ToInt32(txtpage.Text.Substring(0, txtpage.Text.IndexOf('/'))) <= getcount() && recordclicked == true)
                    {
                        this.Resume.Source = new BitmapImage(new Uri("/Images/Record Icons/stop.png", UriKind.RelativeOrAbsolute));
                        message.Text = "Tap to stop recording voice for page " + txtpage.Text.Substring(0, txtpage.Text.IndexOf('/'));
                        StoryReadingExperience.storystackmouseenter(this.messagestk);
                    }
                    else if (Constants.mode == "Rec" && Convert.ToInt32(txtpage.Text.Substring(0, txtpage.Text.IndexOf('/'))) == getcount() + 1 && recordclicked == false)
                    {
                        this.Resume.Source = new BitmapImage(new Uri("/Images/Record Icons/record.png", UriKind.RelativeOrAbsolute));
                        message.Text = "Tap to record voice for page " + txtpage.Text.Substring(0, txtpage.Text.IndexOf('/'));
                        StoryReadingExperience.storystackmouseenter(this.messagestk);
                    }
                    else if (Constants.mode == "Rec" && Convert.ToInt32(txtpage.Text.Substring(0, txtpage.Text.IndexOf('/'))) == getcount() + 1 && recordclicked == true)
                    {
                        this.Resume.Source = new BitmapImage(new Uri("/Images/Record Icons/stop.png", UriKind.RelativeOrAbsolute));
                        message.Text = "Tap to  stop recording voice for page " + txtpage.Text.Substring(0, txtpage.Text.IndexOf('/'));
                        StoryReadingExperience.storystackmouseenter(this.messagestk);
                    }
                    else if (Constants.mode == "Listen" || Constants.mode == "Listenmp3")
                    {
                        StoryReadingExperience.storystackmouseenter(this.messagestk);
                    }

                }
                else
                {
                    buttonpressed = false;
                    return;
                }
            }
            catch (Exception ex)
            {
                Exceptions.SaveOrSendExceptions("Exception in showstack In StoryReading file", ex);
                string excepmess = "Exception in showstack In StoryReading file.\n\n" + ex.Message + "\n\n StackTrace :- \n" + ex.StackTrace;
            }
        }
        private void me_MarkerReached(object sender, TimelineMarkerRoutedEventArgs e)
        {
            try
            {
                XDocument xmlDoc =
                    XDocument.Load("Story Reading Xml/StoryReading.xml");
                var findEle = from i in xmlDoc.Descendants("show") where i.Attribute("id").Value.ToString() == AppSettings.ShowID select i;
                var data = from f in findEle.Descendants("story")
                           where (Convert.ToInt32(f.Attribute("id").Value)) == pagenumber + 1
                           select f;



                if (data.Count() > 0)
                {
                    StackPanel_ManipulationDelta(null, null);
                    StackPanel_ManipulationCompleted(null, null);
                }
            }
            catch (Exception ex)
            {
                Exceptions.SaveOrSendExceptions("Exception in me_MarkerReached In StoryReading file", ex);
                string excepmess = "Exception in me_MarkerReached In StoryReading file.\n\n" + ex.Message + "\n\n StackTrace :- \n" + ex.StackTrace;
            }


        }
        private void me_MediaOpened(object sender, RoutedEventArgs e)
        {
            try
            {
                this.me.Position = new TimeSpan(0, 0, 0, Constants.StartPosition);
                Constants.StartPosition = default(int);
                TimelineMarker endtime = new TimelineMarker();
                endtime.Time = new TimeSpan(0, 0, 0, Constants.EndPosition);
                (sender as MediaElement).Markers.Add(endtime);
                Constants.EndPosition = default(int);
            }
            catch (Exception ex)
            {
                Exceptions.SaveOrSendExceptions("Exception in me_MediaOpened In StoryReading file", ex);
                string excepmess = "Exception in me_MediaOpened In StoryReading file.\n\n" + ex.Message + "\n\n StackTrace :- \n" + ex.StackTrace;
            }
        }

        private void me_CurrentStateChanged(object sender, RoutedEventArgs e)
        {
            try
            {
                if (this.me.CurrentState == MediaElementState.Paused || this.me.CurrentState == MediaElementState.Stopped || this.me.CurrentState == MediaElementState.Closed)
                {
                    message.Text = "           Play";
                    this.Resume.Source = new BitmapImage(new Uri("/Images/Record Icons/play.png", UriKind.RelativeOrAbsolute));
                }
                else if (this.me.CurrentState == MediaElementState.Playing)
                {
                    message.Text = "          Pause";
                    this.Resume.Source = new BitmapImage(new Uri("/Images/Record Icons/pause.png", UriKind.RelativeOrAbsolute));
                }
            }
            catch (Exception ex)
            {
                Exceptions.SaveOrSendExceptions("Exception in me_CurrentStateChanged In StoryReading file", ex);
                string excepmess = "Exception in me_CurrentStateChanged In StoryReading file.\n\n" + ex.Message + "\n\n StackTrace :- \n" + ex.StackTrace;
            }

        }

       
      
      


    }
}